//
//  StrategySecondNearbyViewController.m
//  ITrip
//
//  Created by dllo on 15/5/28.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "StrategySecondNearbyViewController.h"
#import <AFNetworking.h>
#import "URLPath.h"
#import "ParserNearbyModel.h"
#import <UIImageView+AFNetworking.h>
#import "StrategyNearbySecondTableViewCell.h"
#import "StrategyNearbyTravelNotesViewController.h"

@interface StrategySecondNearbyViewController ()<UIAlertViewDelegate>

@property(nonatomic, retain) ParserNearbyModel *parserNearbyModel;

@end

@implementation StrategySecondNearbyViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImage *icon = [UIImage imageNamed:@"iconfont_return"];
    icon = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStyleDone target:self action:@selector(getBack)];
    
    self.view.backgroundColor = [UIColor colorWithRed:227/255.0 green:233/255.0 blue:240/255.0 alpha:1];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    NSString *str = @"攻略";
    title.text = [self.titleName stringByAppendingString:str];
    
    title.font = [UIFont systemFontOfSize:20];
    title.font = [UIFont boldSystemFontOfSize:25];
    title.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = title;
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *path = [[URLPath strategyNearbySecondURL] stringByAppendingFormat:@"%ld.json?page=1", self.numberNearby];
    NSLog(@"%@", path);
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        self.parserNearbyModel = [[ParserNearbyModel alloc] init:dic];
        [self createMyView];
        [activityIndicator stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        [activityIndicator stopAnimating];
        alert.delegate = self;
        [alert show];
    }];
    
   
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *path = [[URLPath strategyNearbySecondURL] stringByAppendingFormat:@"%ld.json?page=1", self.numberNearby];
    NSLog(@"%@", path);
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        self.parserNearbyModel = [[ParserNearbyModel alloc] init:dic];
        [self createMyView];
        [activityIndicator stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        [activityIndicator stopAnimating];
        alert.delegate = self;
        [alert show];
    }];
}

- (void)getBack
{
//    self.tabBarController.tabBar.hidden = NO;
//    self.tabBarController.tabBar.translucent = NO;
    [self.navigationController popViewControllerAnimated:YES];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    StrategyNearbySecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[StrategyNearbySecondTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.contentView.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, self.view.frame.size.width, cell.frame.size.height);
    }
    
    for (UIImageView *view in cell.photo_url.subviews) {
        [view removeFromSuperview];
    }
    
    cell.descripLabel.text = nil;
    
    ParserNearbyAttraction_trip_tags *parser = self.parserNearbyModel.attraction_trip_tags[indexPath.section];
    [cell setParserNearbyAC:parser.attraction_contents[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
 
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ParserNearbyAttraction_trip_tags *parser = self.parserNearbyModel.attraction_trip_tags[indexPath.section];
    ParNearbyAttraction_contents *contents = parser.attraction_contents[indexPath.row];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName];
    CGRect frame = [contents.descrip boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    if (contents.notes.count > 0) {
        return 150 + frame.size.height + 70;
    }
    return frame.size.height + 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.parserNearbyModel.attraction_trip_tags.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    ParserNearbyAttraction_trip_tags *par = self.parserNearbyModel.attraction_trip_tags[section];
    return par.attraction_contents.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ParserNearbyAttraction_trip_tags *par = self.parserNearbyModel.attraction_trip_tags[section];
    UILabel *sectionLable = [[UILabel alloc] init];
    sectionLable.text = par.name;
    sectionLable.textAlignment = NSTextAlignmentCenter;
    sectionLable.font = [UIFont boldSystemFontOfSize:16];
    sectionLable.backgroundColor = [UIColor whiteColor];
    return sectionLable;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (void)createMyView
{
    mySecondNearbyTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    mySecondNearbyTable.delegate = self;
    mySecondNearbyTable.dataSource = self;
    [self.view addSubview:mySecondNearbyTable];
    mySecondNearbyTable.backgroundColor = [UIColor clearColor];
    
    // tableHeaderView
    UIView *headerView = [[UIView alloc] init];
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.backgroundColor = [UIColor whiteColor];
    
    [button1 setImage:[UIImage imageNamed:@"iconfont-tupian"] forState:UIControlStateNormal];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.backgroundColor = [UIColor whiteColor];
    [button2 setImage:[UIImage imageNamed:@"iconfont-bijiben_blue"] forState:UIControlStateNormal];
    headerView.backgroundColor = [UIColor colorWithRed:227/255.0 green:233/255.0 blue:240/255.0 alpha:1];
    
    UIImageView *image_url = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    image_url.contentMode = UIViewContentModeScaleToFill;
    [image_url setImageWithURL:[NSURL URLWithString:self.parserNearbyModel.image_url] placeholderImage:nil];
    UIImageView *placeIcon = [[UIImageView alloc] initWithFrame:CGRectMake(20, image_url.frame.size.height - 50, 30, 30)];
    placeIcon.backgroundColor = [UIColor clearColor];
    [placeIcon setImage:[UIImage imageNamed:@"iconfont-weizhicaiji"]];
    [image_url addSubview:placeIcon];
    UILabel *name_zh_cn = [[UILabel alloc] initWithFrame:CGRectMake(60, image_url.frame.size.height - 55, image_url.frame.size.width - 60, 15)];
    UILabel *name_en = [[UILabel alloc] initWithFrame:CGRectMake(60, image_url.frame.size.height - 30, image_url.frame.size.width - 60, 15)];
    name_en.textColor = [UIColor whiteColor];
    name_zh_cn.textColor = [UIColor whiteColor];
    name_zh_cn.text = self.parserNearbyModel.name_zh_cn;
    name_en.text = self.parserNearbyModel.name_en;
    [image_url addSubview:name_zh_cn];
    [image_url addSubview:name_en];
    
    button1.frame = CGRectMake(0, image_url.frame.size.height, self.view.frame.size.width / 2.0, 80);
    button2.frame = CGRectMake(self.view.frame.size.width / 2.0, image_url.frame.size.height, self.view.frame.size.width / 2.0, 80);
    
    [button1 setTitle:[NSString stringWithFormat:@"%ld张图片", self.parserNearbyModel.photos_count] forState:UIControlStateNormal];
    [button2 setTitle:[NSString stringWithFormat:@"%ld篇游记", self.parserNearbyModel.attraction_trips_count] forState:UIControlStateNormal];
//    [button1 setImage:nil forState:UIControlStateNormal];
//    [button2 setImage:nil forState:UIControlStateNormal];
    [button1 setTitleEdgeInsets:UIEdgeInsetsMake(0, -35, -30, 0)];
    [button1 setImageEdgeInsets:UIEdgeInsetsMake(-30, 20, 0, -50)];
    [button2 setTitleEdgeInsets:UIEdgeInsetsMake(0, -35, -30, 0)];
    [button2 setImageEdgeInsets:UIEdgeInsetsMake(-30, 20, 0, -50)];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(showPicture) forControlEvents:UIControlEventTouchUpInside];
    [button2 addTarget:self action:@selector(showTravel) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *descrip = [[UILabel alloc] initWithFrame:CGRectMake(20, button1.frame.origin.y + button1.frame.size.height + 20, self.view.frame.size.width - 40, 30)];
    descrip.font = [UIFont systemFontOfSize:16];
    descrip.text = self.parserNearbyModel.descrip;
    descrip.textColor = [UIColor blackColor];
    descrip.numberOfLines = 1000;
    [descrip sizeToFit];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName];
    CGRect frame = [self.parserNearbyModel.descrip boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
    headerView.frame = CGRectMake(0, 0, self.view.frame.size.width, frame.size.height + 320);
    [headerView addSubview:image_url];
    [headerView addSubview:button1];
    [headerView addSubview:button2];
    [headerView addSubview:descrip];
   
    
    mySecondNearbyTable.tableHeaderView = headerView;
    [image_url release];
    [name_en release];
    [name_zh_cn release];
    [mySecondNearbyTable release];
}

- (void)showPicture
{
    StrategyNearbyPhotoViewController *photo = [[StrategyNearbyPhotoViewController alloc]init];
    photo.titleName = self.titleName;
    photo.numberid = self.numberNearby;
    [self.navigationController pushViewController:photo animated:YES];
}

- (void)showTravel
{
    StrategyNearbyTravelNotesViewController *travelNotes = [[StrategyNearbyTravelNotesViewController alloc] init];
    
    travelNotes.title = self.titleName;
    travelNotes.travelNotesId = self.numberNearby;
    [self.navigationController pushViewController:travelNotes animated:YES];
    [travelNotes release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
